<?php

/*
=====================================================
ExpressionEngine-bypMachine
-----------------------------------------------------
http://www.pmachine.com/
-----------------------------------------------------
Copyright(c)2003-2004pMachine,Inc.
=====================================================
THISISCOPYRIGHTEDSOFTWARE
PLEASEREADTHELICENSEAGREEMENT
http://www.pmachine.com/expressionengine/license.html
=====================================================
File:mod.ncaggregator.php
-----------------------------------------------------
Purpose:rssadisplayclass
=====================================================

EXAMPLE:

read _readme.txt (:

*/

//error_reporting(0);
$spath=explode("/",$_SERVER['PHP_SELF']);
$_spath=($spath[1]=="eu" || $spath[1]=="de" || $spath[1]=="fr" || $spath[1]=="es")?"/".$spath[1]:"";

require_once($_SERVER['DOCUMENT_ROOT'].$_spath.'/system/multifeeds/rss_fetch.inc');

class Ncaggregator{
  var $return_data	='';
  var $data='';
  var $feed='';
  var $content='';
  var $title='';
  var $link='';
  var $date='';
  var $where='';
  var $_limit='';


  //------------------------------------------
  //let's fill the string with missing taggies
  //------------------------------------------
  function autoclose($txt){

  	//---------------------------------
  	//define vars
  	//---------------------------------
  	$singles=array('br','img','input','hr');
  	$tags='';

  	//---------------------------------
  	//find opened tags
  	//---------------------------------
      	preg_match_all("/<(([A-Z]|[a-z]).*)(( )|(>))/isU",$txt,$otags);
      	$_otags=$otags[1];
      	$_otags=array_reverse($_otags);

      	//---------------------------------
      	//find closed tags
      	//---------------------------------
      	preg_match_all("/<\/(([A-Z]|[a-z]).*)(( )|(>))/isU",$txt,$ctags);
  	$_ctags=$ctags[1];


  	//---------------------------------
  	//remove singles from opened ones
  	//---------------------------------
  	for($i=0;$i<count($_otags);$i++){
  		if(in_array($_otags[$i],$singles))
  			unset($_otags[$i]);
  	}
  	$_otags=array_values($_otags);


  	//---------------------------------
  	//check for unclosed tags
  	//---------------------------------
  	for($i=0;$i<count($_otags);$i++){
  		if(in_array($_otags[$i],$_ctags)){
  			unset($_ctags[array_search($_otags[$i],$_ctags)]);
  		}else{
  			$tags.="</".$_otags[$i].">";
  		}
  	}

  	//---------------------------------
  	//output
  	//---------------------------------
  	return $tags;
  }



  //------------------------------------------
  //let's count all these pretty wordies
  //------------------------------------------
  function castrate($str,$ipath,$elpath){

  	//---------------------------------
  	//define vars
  	//---------------------------------
    global $TMPL, $IN, $FNS;
    $num=$TMPL->fetch_param('content-limit');
    $num=(!$num)?100:$num;
    $skiptags=$TMPL->fetch_param('skip-tags');
    $_skiptags=array();
    $res=array();
   	$hrefs=array();
    $n_tags=array();
    $n_links=array();
    $pattern=array();
    $lnum='';
    $tnum='';
    $cut=0;
	  $ipath=($ipath{strlen($ipath)-1}=="/")?substr($ipath,0,-1):$ipath;

    	//---------------------------------
    	//prepare input + replace <tags>
    	//---------------------------------
      preg_match_all("%<a.*?\/a>%",$str,$v_links);
      $str=preg_replace("%<a.*?\/a>%","[link]",$str);
      preg_match_all("%<.*?>%",$str,$v_tags);
      $str=preg_replace("%<.*?>%"," [tag] ",$str);
      $str=trim(rtrim(str_replace("  "," ",$str)));


      //---------------------------------
      //split to words & clean $res
      //---------------------------------
      $res=explode(" ",$str);
      for($i=0;$i<count($res);$i++){
        if(strlen($res[$i])==0)unset($res[$i]);
      }
      $res=array_values($res);


      //---------------------------------
    	//count tags
    	//---------------------------------
      for($i=0,$j=0,$k=0;$i<count($res);$i++){
        if(substr($res[$i],0,6)=="[link]"){
    			$hnum[]=count(explode(" ",preg_replace("%<a.*?>(.*?)<\/a>%","$1",$v_links[0][$j])));
    			$n_links[]=$i;
    			$j++;
    		}
    		if(substr($res[$i],0,5)=="[tag]"){
    			$n_tags[]=$i;
    			$k++;
    		}
      }

    	//---------------------------------
    	//cut all the crap off
    	//---------------------------------
      for($i=0,$j=0,$k=0;$i<count($res);$i++){
        $pattern=array('<', ',', '!', '.', '/', '>', '#', '-', ':', ';');
        if(!in_array($res[$i]{0},$pattern) && !strstr($res[$i],'[tag]')){
          if(strstr($res[$i],'[link]')){
             $j=$j+$hnum[$k];
             $k++;
          }else{
              $j++;
          }
    		}
    		if($j>=$num){
          array_splice($res,$i+1);
          break;
        }
      }

      //---------------------------------
    	//place <tag>s back into the array
    	//---------------------------------
      for($i=0;$i<count($n_tags);$i++){
        $tnum=$n_tags[$i];
        if(isset($res[$tnum]))$res[$tnum]=str_replace("[tag]",$v_tags[0][$i],$res[$tnum]);
      }
      for($i=0;$i<count($n_links);$i++){
        $lnum=$n_links[$i];
        if(isset($res[$lnum]))$res[$lnum]=str_replace("[link]",$v_links[0][$i],$res[$lnum]);
      }


      //---------------------------------
    	//joining array
    	//---------------------------------
      $res=implode(" ",$res);
      $res=preg_replace("%(<.*?>)%","$1",preg_replace("%(<.*?>)%","$1",$res));

      //---------------------------------
    	//tag removal
    	//---------------------------------
      if(strlen($skiptags)>0&&!strstr($skiptags,"all")){
        $_skiptags=explode("|",$skiptags);
        for($i=0;$i<count($_skiptags);$i++){
          $res=preg_replace(array("%<$_skiptags[$i].*?>%","%<\/$_skiptags[$i].*?>%"),array("",""),$res);
        }
      }elseif(strstr($skiptags,"all")){
        $res=preg_replace(array("%<.*?>%","%<\/.*?>%"),array("",""),$res);
      }

      //---------------------------------
    	//postprocessing
    	//---------------------------------
      $res=preg_replace("%(<\w.*?>)%"," $1",preg_replace("%(</\w.*?>)%","$1 ",$res));
    	$res=str_replace(">  <","> <",$res);
      $res=trim(rtrim($res));
      $res=str_replace(array("src='/",'src="/'),array("src='".$ipath."/",'src="'.$ipath.'/'),$res);


    	//---------------------------------
    	//output
    	//---------------------------------
      $ending=$this->autoclose($res);
      return $res."...".$ending;

}





  //------------------------------------------
  //date thingy
  //------------------------------------------
  function date_me($date,$format){
    global $TMPL, $IN, $FNS;
    $newdate='';
    $_newdate='';
    $_date=array();
    $__date=array();
    $lang=$TMPL->fetch_param('lang');
    if($lang=="fr"){
        setlocale(LC_TIME,'french');
        //$month=array('jan','fév','mar','avr','mai','jun','jui','aoû','sep','oct','nov','déc');
    }elseif($lang=="de"){
        setlocale(LC_TIME,'german');
        //$month=array('Jan','Feb','Mär','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez');
    }elseif($lang=="es"){
        setlocale(LC_TIME,'spanish');
       // $month=array('ene','feb','mar','abr','may','jun','jul','ago','sep','oct','nov','dic');
    }else{
        //$month=array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
    }

    $date=str_replace(":"," ",preg_replace("%.*?\, (.*?)\+\d{4}%","$1",$date));
    $_date=explode(" ",$date);
    //for($i=1;$i<13;$i++){
    //  if($_date[1]==$month[$i-1]){
    //    $_date[1]=$i;
    //    break;
    //  }
    //}

    $_newdate= utf8_encode(strftime($format, mktime($_date[3], $_date[4], $_date[5], $_date[1], $_date[0], $_date[2])));
    return $_newdate;
    setlocale(LC_TIME,'english');
  }


    //------------------------------------------
    //constructor
    //------------------------------------------
    function Ncaggregator(){
      //------------------------------
      //set globals & other vars
      //------------------------------
      global $DB, $TMPL, $IN, $FNS;
      $_where='';
    	$fin=array();
    	$fout=array();
    	$feed='';
      $content='';
      $title='';
      $link='';
      $date='';
      $rss='';
      $__blob='';

      $limit=$TMPL->fetch_param('limit');
      $limit=(!$limit)?5:$limit;
      $feeds=explode("|",str_replace("not ","-",$TMPL->fetch_param('feeds')));
        foreach($feeds as &$v){
          if($v!=="")($v>=0)?$fin[]=$v:$fout[]=-$v;
        }
      $order=$TMPL->fetch_param('orderby');
      $sort=$TMPL->fetch_param('sortby');

      //--------------------------
      // feeds selection
      //--------------------------

      if(count($fin)>0 || count($fout)>0){
        $_where="WHERE ";
      }

      if(count($fin)>0){
      $_where.=($fout)?"(":"";
        for($i=0;$i<count($fin);$i++){
           $_where.='feed_id="'.$fin[$i].'"';
           if($i!==(count($fin)-1)){
              $_where.=" OR ";
           }
        }
      }
      if(count($fout)>0){
        $_where.=($fin)?")AND ":"";
        for($i=0;$i<count($fout);$i++){
           $_where.='feed_id!="'.$fout[$i].'"';
           if($i!==(count($fout)-1)){
              $_where.=" AND ";
          }
        }
      }

      //---------------------------
      //limit entries per feed
      //---------------------------
      if($limit>=0){
         $_limit=$limit;
      }

      //---------------------------
      //order entries
      //---------------------------
     $_order=($order=="id")?"feed_id,feed_order":"feed_order,feed_id";


      //------------------------------
      //fetch data
      //-------------------------------
      preg_match("/".LD."feed".RD."(.+?)".LD.SLASH."feed".RD."/s", $TMPL->tagdata, $match);
      $query = $DB->query('SELECT * FROM exp_feeds '.$_where.' ORDER BY '.$_order.';');
      $z=0;
      foreach($query->result as $row){
        $rss = fetch_rss($row['feed_url']);
        for($z=0;$z<$_limit;$z++){
        	if($z<count($rss->items)){
	          if($rss->items[$z]){
	            $_blob[$z]=str_replace(array('{feed-title}',
	                                     '{entry-title}',
	                                     '{entry-link}',
	                                     '{entry-content}'),
	                                array($row['feed_name'],
	                                      $rss->items[$z]['title'],
	                                      $rss->items[$z]['link'],
	                                      $this->castrate($rss->items[$z]['summary'],$rss->channel['link'],$rss->items[$z]['link'])),
	                                      $match[1]);
	            preg_match('%{entry-date format="(.*?)"}%',$_blob[$z],$dateformat);
	            $_dateformat=$this->date_me($rss->items[$z]['pubdate'],$dateformat[1]);
	            $_datesorter=$this->date_me($rss->items[$z]['pubdate'],"%Y%m%d%H%M%S");
	            $_blob[$z]=preg_replace('%{entry-date format="(.*?)"}%',$_dateformat,$_blob[$z]);
							$blobSorter[]=array($_datesorter,$_blob[$z]);
						
	          }
	        }
				}
      }

      

      if($order=="date"){
	      foreach ($blobSorter as $k=>$v) {
				    $sDate[$k]  = $v[0];
				    $sData[$k] = $v[1];
				}
				
				if($sort=="asc"){
					array_multisort($sDate, SORT_NUMERIC, SORT_ASC, $blobSorter);
				}else{
					array_multisort($sDate, SORT_NUMERIC, SORT_DESC, $blobSorter);
				}
				
			}
			
			
			foreach ($blobSorter as $k=>$v){
				  $__blob.=$blobSorter[$k][1];
			}	

			

			
      $this->return_data =&preg_replace("/".LD."feed".RD."(.+?)".LD.SLASH."feed".RD."/s",$__blob,$TMPL->tagdata);
    }
}


// END CLASS
?>
